﻿#include "TcpSocket.h"

#ifdef _WIN32

bool TcpSocket::Create(TcpSocket::Desc desc)
{
	WSADATA wsadata;
	if (0 != WSAStartup(MAKEWORD(2, 2), &wsadata))//windows�첽�׽�������
	{
		printf("[error]WSAStarup failed,code %d\n", WSAGetLastError());
		return 0;
	}

    sock = socket(desc.af, desc.type, desc.protocol);//����һ���յ�socket
    if (INVALID_SOCKET == sock)
	{
		LOGI("Was invalied sock");
		return 0;
	}

    LOGI("create socket successfully");
    struct sockaddr_in addr;
    addr.sin_family = desc.sinFamily;
	addr.sin_port = htons(desc.port);
	addr.sin_addr.S_un.S_addr = inet_addr(desc.host);

    if (INVALID_SOCKET == connect(sock, (struct sockaddr*)&addr, sizeof(addr)))
	{
		LOGI("Failed to connect the socket %s %d", desc.host, desc.port);
        return false;
	}
    LOGI("create tcpClient successfully connect to  %s:%d", desc.host, desc.port);

    return true;
}

void TcpSocket::Close()
{
    closesocket(sock);// close socket
    WSACleanup();
}

#endif // _WIN32


#ifdef __linux__
bool TcpSocket::Create(TcpSocket::Desc desc)
{

    sock = socket(desc.af, desc.type, desc.protocol); // ??????socket
    if (-1 == sock)
    {
        LOGI("get an invalied sock", "");
        return false;
    }
    LOGI("create socket successfully");

    struct sockaddr_in addr;
    addr.sin_family = desc.sinFamily;
    addr.sin_port = htons(desc.port);
    addr.sin_addr.s_addr = inet_addr(desc.host);

    if (-1 == connect(sock, (struct sockaddr *)&addr, sizeof(addr)))
    {
        LOGI("Failed to connect the socket %s %d", desc.host, desc.port);
        return false;
    }
    LOGI("create tcpClient successfully connect to  %s:%d", desc.host,desc.port);

    return true;
}

void TcpSocket::Close()
{
    close(sock); // ??
}
#endif
